import React, { useEffect, useState } from 'react';
import { Button, Space, message, Modal, Tooltip } from 'antd';
import { DownloadOutlined, DeleteOutlined } from '@ant-design/icons';
import DraggableTable from './DraggableTable';
import request from '@/utils/request';

const AdvancedDataTable = ({
  dataKey,
  advancedDataId = 1,
  pageSize,
  page,
  total,
  onPageChange,
  onRefresh,
  tableScrollY,
  onDataChange,
  onSelectedRowKeysChange
}) => {
  const [columns, setColumns] = useState([]);
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  // 拉取数据
  const fetchData = async (curPage = page, size = pageSize) => {
    if (!dataKey) return;
    setLoading(true);
    // 默认字段
    const defaultColumns = [
      {
        title: '文件名',
        dataIndex: 'file_name',
        key: 'file_name',
		width: 180,
        ellipsis: { showTitle: false },
        render: (text) => (
          <Tooltip title={text}>
            <div style={{ cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{text}</div>
          </Tooltip>
        )
      },
      {
        title: '文件路径',
        dataIndex: 'file_path',
        key: 'file_path',
		width: 180,
        ellipsis: { showTitle: false },
        render: (text) => (
          <Tooltip title={text}>
            <div style={{ cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{text}</div>
          </Tooltip>
        )
      },
      {
        title: '文件大小',
        dataIndex: 'data_size',
        key: 'data_size',
		width: 80,
        ellipsis: { showTitle: false },
        render: (text) => (
          <Tooltip title={text}>
            <div style={{ cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{text}</div>
          </Tooltip>
        )
      },
      {
        title: '归档时间',
        dataIndex: 'archive_time',
        key: 'archive_time',
		width: 180,
        ellipsis: { showTitle: false },
        render: (text) => (
          <Tooltip title={text}>
            <div style={{ cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{text}</div>
          </Tooltip>
        )
      },
      {
        title: '状态',
        dataIndex: 'bk_pstate',
        key: 'bk_pstate',
		width: 80,
        ellipsis: { showTitle: false },
        render: (text) => (
          <Tooltip title={text}>
            <div style={{ cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{text}</div>
          </Tooltip>
        )
      }
    ];
    try {
      const res = await request.get('/Management/AdvancedDataList', {
        params: {
          advanced_data_id: advancedDataId,
          data_key: dataKey,
          page_size: size,
          page: curPage
        }
      });
      if (res.status === 200 && res.data.data) {
        const { columns: colArr = [], list = [], count = 0 } = res.data.data;
        // 合并默认字段和后端字段，默认字段优先，去重
        const allColArr = [
          ...defaultColumns.map(col => col.dataIndex),
          ...colArr.filter(col => !defaultColumns.some(def => def.dataIndex === col))
        ];
        // 动态生成columns
        const dynamicColumns = allColArr.map((col) => {
          const defaultCol = defaultColumns.find(def => def.dataIndex === col);
          if (defaultCol) return defaultCol;
          return {
            title: col,
            dataIndex: col,
            key: col,
			width: 100,
            ellipsis: { showTitle: false },
            render: (text) => (
              <Tooltip title={text}>
                <div style={{ cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{text}</div>
              </Tooltip>
            )
          };
        });
        // 固定操作列
        dynamicColumns.push({
          title: '操作',
          key: 'action',
          width: 180,
          fixed: 'right',
          render: (_, record) => (
            <Space>
              <Button size="small" icon={<DownloadOutlined />} onClick={() => handleDownload(record)}>
                下载
              </Button>
              <Button size="small" danger icon={<DeleteOutlined />} onClick={() => handleDelete(record)}>
                删除
              </Button>
            </Space>
          )
        });
        setColumns(dynamicColumns);
        // 数据加key
        const tableData = list.map((item, idx) => ({
          ...item,
          key: item.product_id ? item.product_id : `${dataKey}_${idx}`
        }));
        setData(tableData);
        if (onDataChange) {
          onDataChange(tableData);
        }
      }
    } catch (e) {
      message.error(e?.message || '获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  React.useEffect(() => {
    fetchData(page, pageSize);
    // eslint-disable-next-line
  }, [dataKey, page, pageSize]);

  // 下载
  const handleDownload = (record) => {
    if (!record.product_id) {
      message.warning('缺少product_id，无法下载');
      return;
    }
    const url = request.getUrl(`/Management/Download?data_type=other&product_id=${record.product_id}`);
    window.open(url, '_blank');
  };

  // 删除
  const handleDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除文件"${record.file_name || record['文件名']}"吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const payload = {
            files: [
              {
                data_type: 'other',
                product_id: record.product_id
              }
            ]
          };
          const res = await request.post('/Management/DataDelete', payload);
          if (res.status === 200) {
            message.success('删除成功');
            fetchData(page, pageSize);
            if (onRefresh) onRefresh();
          }
        } catch (e) {
          message.error(e?.message || '删除失败');
        }
      }
    });
  };

  // 多选
  const rowSelection = {
    selectedRowKeys,
    columnWidth: 50,
    onChange: (keys) => {
      setSelectedRowKeys(keys);
      if (onSelectedRowKeysChange) {
        onSelectedRowKeysChange(keys);
      }
    }
  };

  return (
    <DraggableTable
      rowSelection={rowSelection}
      columns={columns}
      dataSource={data}
      pagination={false}
      tableLayout="fixed"
      style={{ flex: 1 }}
      scroll={{ y: tableScrollY, x: 'max-content' }}
      bordered
      size="small"
      loading={loading}
      rowClassName={(_, index) => (index % 2 === 0 ? 'zebra-row-odd' : 'zebra-row-even')}
      onColumnsChange={(columns) => {
        setColumns(columns);
      }}
    />
  );
};

export default AdvancedDataTable; 